using Godot;
using System;

public partial class Player : Sprite2D
{
    private float speed = 500; // 人物移动速度
    public PackedScene bulletPrefab;
    private Timer shootTimer; // 发射间隔计时器
    private bool canShoot = true; // 是否可以发射子弹

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        bulletPrefab = GD.Load<PackedScene>("res://prefabs/bullet.tscn");
        shootTimer = GetNode<Timer>("ShootTimer"); // 获取计时器节点
        shootTimer.Connect("timeout", new Callable(this, nameof(OnShootTimerTimeout))); // 连接计时器的 timeout 信号
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
    {
        float movement = speed * (float)delta;
        if (Input.IsKeyPressed(Key.Shift))
        {
            movement /= 2;
        }

        if (Input.IsKeyPressed(Key.Left))
        {
            this.Position += new Vector2(-movement, 0);
        }
        if (Input.IsKeyPressed(Key.Right))
        {
            this.Position += new Vector2(movement, 0);
        }
        if (Input.IsKeyPressed(Key.Up))
        {
            this.Position += new Vector2(0, -movement);
        }
        if (Input.IsKeyPressed(Key.Down))
        {
            this.Position += new Vector2(0, movement);
        }
        if (Input.IsKeyPressed(Key.Z) && canShoot)
        {
            Shoot();
        }
    }

    // 发射子弹
    private void Shoot()
    {
        var bullet = bulletPrefab.Instantiate() as Node2D;
        GetParent().AddChild(bullet);
        bullet.Position = this.Position; // 设置子弹的初始位置

        canShoot = false; // 禁止发射
        shootTimer.Start(); // 启动计时器
    }

    // 计时器结束时调用
    private void OnShootTimerTimeout()
    {
        canShoot = true; // 允许发射
    }
}